# -*- coding: utf-8 -*-
"""
@Time    : 2022/9/15 17:39
@Author  : huanghuang
"""
from fastapi import APIRouter, Body, UploadFile, Form
from fastapi.responses import FileResponse
from urllib.parse import unquote

from schema.req_schema.utils_schema import GenerateExcelRequestModel, UseNameOrIndexEnum, GeneratePdfRequestModel
from common.pkg.qrcode_util import generate_qrcode
from common.pkg.excel_util import generate_excel, read_data_from_excel
from common.pkg.pdf_util import generate_pdf
from common.pkg.str_id import get_short_uuid
from common.utils.resp import JsonResponse


router = APIRouter(prefix="/utils")


@router.post("/generate_qrcode", description="根据传入的字符串生成二维码返回")
def openapi_generate_qrcode(content: str = Body(..., embed=True)):
    content = unquote(content, "utf-8")
    filename = generate_qrcode(content)
    return FileResponse(filename)


@router.post("/generate_excel", description="根据传入的数据生成excel返回")
def openapi_generate_excel(excel_model: GenerateExcelRequestModel = Body()):
    _filename = generate_excel(excel_model.header, excel_model.data, excel_model.sheet_name)
    response = FileResponse(_filename)
    response.media_type = "xlsx"
    response.headers["Content-Type"] = "application/vnd.ms-excel; charset=UTF-8"
    response.headers["Content-Disposition"] = f"attachment; filename={excel_model.filename or get_short_uuid()}.xlsx"
    return response


@router.post("/read_from_excel", description="从excel读取数据")
def openapi_read_data_from_excel(excel_file: UploadFile,
                                 use_name_or_index: UseNameOrIndexEnum = Form("name",
                                                                              description="使用header中的名字还是直接使用index")):
    data = read_data_from_excel(excel_file.file.read(), use_name_or_index.value)
    return JsonResponse(data=data).to_response()


@router.post("/generate_pdf", description="给定一个url或者html内容生成pdf返回,如果给了callback_url则异步返回[使用post方法],否则同步返回")
def openapi_generate_pdf(pdf_request_model: GeneratePdfRequestModel):
    source = pdf_request_model.url or pdf_request_model.html
    # if pdf_request_model.callback_url:
    #     # 创建一个异步任务,使用post方法请求callback_url 并且将文件带上,看是否需要入库做持久化吧
    #     generate_and_send_pdf.delay(source, pdf_request_model.callback_url)
    #     return JsonResponse().to_response()
    # else:
    filename = generate_pdf(source=source)
    return FileResponse(filename)
